package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.RoomMapper;
import com.fuego.creditsystemcommodity.service.IRoomInfoService;
import com.fuego.creditsystemcommodity.service.IRoomService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.House;
import org.example.entity.Room;
import org.example.entity.RoomInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.example.utils.RedisConstants.ROOM_INFO_STOCK_KEY;


@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IRoomInfoService roomInfoService;

    @Override
    public Result queryRoomOfHotel(Long hotelId) {
        // 查询优惠券信息
        List<Room> rooms = getBaseMapper().queryRoomOfHotel(hotelId);
        // 返回结果
        return Result.ok(rooms);
    }

    @Override
    @Transactional
    public void addRoomInfo(Room room) {
        // 保存优惠券
        save(room);
        // 保存秒杀信息
        RoomInfo roomInfo = new RoomInfo();
        roomInfo.setRoomId(room.getId());
        roomInfo.setStock(room.getStock());

        roomInfoService.save(roomInfo);
        //保存秒杀库存到redis中
        stringRedisTemplate.opsForValue().set(ROOM_INFO_STOCK_KEY+room.getId(),room.getStock().toString());
    }

    @Override
    public Result queryAllRoom() {
        List<Room> rooms = getBaseMapper().queryAllRoom();
        // 返回结果
        return Result.ok(rooms);
    }

    @Override
    public Result queryRoomById(Long roomId) {
        List<Room> rooms = getBaseMapper().queryRoomById(roomId);


        // 返回结果
        return Result.ok(rooms);
    }

    public Result pageRoom(Integer page, Integer pageSize){
        Map<String,Object> resultMap = new HashMap<>();
        try {
            PageHelper.startPage(page,pageSize);
            List<Room> rooms = getBaseMapper().queryAllRoom();
            PageInfo<Room> pageInfo = new PageInfo<>(rooms);

            resultMap.put("rooms",rooms);
            resultMap.put("total",pageInfo.getTotal());
        } catch (Exception e) {
            throw  new RuntimeException(e.getMessage());
        } finally {
            PageHelper.clearPage();
        }
        return Result.ok(resultMap);
    }

    public Result searchRoom(String roomName) {
        List<Room> rooms = getBaseMapper().searchRoom(roomName);
        return Result.ok(rooms);
    }
}
